<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\api\controller;
use think\Controller;
use think\Db;

/**
 * 充值控制器
 */
class Recharge extends ApiBase
{

	//充值接口
	public function charge_number(){
		$mid = input("wallet_id");//货币ID
		$address = input("address");//转出地址
		$number = input("number");//数量
		$password = input("password");//密码
		$symbol = input("symbol");//标志
		//if(empty($mid) || empty($address) || empty($number) || empty($symbol) || empty($password)){
		//	return $this->apiReturn(['code'=>1,'msg'=>lang("参数错误")]);
		//}
        if(empty($mid)){
        	return $this->apiReturn(['code'=>1,'msg'=>lang("请选择充值货币")]);
        }
      	if(empty($symbol)){
        	return $this->apiReturn(['code'=>1,'msg'=>lang("请选择充值货币标志")]);
        }
        if(empty($address)){
        	return $this->apiReturn(['code'=>1,'msg'=>lang("转出地址错误")]);
        }
        if(empty($number)){
        	return $this->apiReturn(['code'=>1,'msg'=>lang("数量错误")]);
        }
        if($number < 0.1){
        	return $this->apiReturn(['code'=>1,'msg'=>lang("充值数量必须大于等于0.1")]);
        }
        if(empty($password)){
        	return $this->apiReturn(['code'=>1,'msg'=>lang("请输入密码")]);
        }
      
        
		$userid = decoded_user_token(input("user_token"),'member_id');
        $exchange_rate = Db::name("wallet")->where(["id"=>$mid])->find()['parities'];
      	$coin_number = $number / $exchange_rate;
      
		//验证密码
		$coin_users_address = Db::name("coin_users_address")->where(["symbol"=>$symbol,"address"=>$address,"userid"=>$userid])->find();

		if($coin_users_address['password'] != $password){
			return $this->apiReturn(['code'=>1,'msg'=>lang("钱包密码错误")]);
		}
		$password = $coin_users_address['password_t'];//平台密码
		
		$to = Db::name("wallet")->where("id",$mid)->find()['wallet_address'];
		if(strtolower($symbol) == "eth"){
			//ETH转账
			$res = ETH_URL."/index/geth/sendTransaction.html";
			$ch = curl_init();
	        curl_setopt($ch, CURLOPT_URL,$res);
	        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
	        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ; // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回    
	        curl_setopt($ch, CURLOPT_POST, 1);
	  	    $post_data = array(
	     		"from_address" => $address,
	     		"to_address" => $to,
	     		"tr_value" => $coin_number,
	     		"pass" => $password,
	     		"gasLimit" => 61000
		    );
		    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
	        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 开启使用SSL
	        $result = curl_exec($ch);
	        curl_close($ch);
			$result = json_decode($result,true);
			if(!empty($result['status']) && $result['status'] == 1){
				$status = 0;
				$msg = lang("转账中");
				$tx = $result['result'];
              	$hash = $result['data'];
			}else{
				$status = 1;
				if($result['msg'] == 'insufficient funds for gas * price + value'){
					$msg = lang("钱包余额不足");
				}else{
					$msg = lang($result['msg']);
				}
			}
		}elseif(strtolower($symbol) == "btc"){
			//BTC转账
			$res = BTC_URL."/index/usdt/sendfrom";
			$ch = curl_init();
	        curl_setopt($ch, CURLOPT_URL,$res);
	        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
	        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ; // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回    
	        curl_setopt($ch, CURLOPT_POST, 1);
	  	    $post_data = array(
	     		"from" => $address,
	     		"to" => $to,
	     		"number" => $coin_number,
	     		"password" => $password
		    );
		    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
	        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 开启使用SSL
	        $result = curl_exec($ch);
	        curl_close($ch);
			$result = json_decode($result,true);
			if(!empty($result['status']) && $result['status'] == 1){
				$status = 0;
				$msg = lang("转账中");
				$tx = $result['data'];
                $hash = $result['data'];
			}else{
				$status = 1;
				$msg = lang($result['msg']);
			}
		}elseif(strtolower($symbol) == "usdt"){
			//USDT转账
			$res = BTC_URL."/index/usdt/omni_funded_send";
			$ch = curl_init();
	        curl_setopt($ch, CURLOPT_URL,$res);
	        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
	        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ; // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回    
	        curl_setopt($ch, CURLOPT_POST, 1);
	  	    $post_data = array(
	     		"from" => $address,
	     		"to" => $to,
	     		"propertyid" => 31,
	     		"feeaddress" => $address,
	     		"number" => $coin_number,
	     		"password" => $password
		    );
		    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
	        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 开启使用SSL
	        $result = curl_exec($ch);
	        curl_close($ch);
			$result = json_decode($result,true);
			if(!empty($result['status']) && $result['status'] == 1){
				$status = 0;
				$msg = lang("转账中");
				$tx = $result['data'];
                $hash = $result['data'];
			}else{
				$status = 1;
				$msg = lang($result['msg']);
			}
		}
		if($status == 0){
            
          	
            $data['to_wallet_id'] = 1;
			$data['form_wallet_id'] = $mid;
	        $data['user_id'] = $userid;
	        $data['type'] = 10;
	        $data['hash'] = $tx;
            $data['hash_tx'] = $hash;
	        $data['from'] = $address;
	        $data['to'] = $to;
            $data['exchange_rate'] = $exchange_rate;
            $data['number'] = $number;
	        $data['coin_number'] = $coin_number;
	        $data['create_time'] = time();
	        $data['update_time'] = time();
	        $data['state'] = 0;
	        $data['is_coin'] = 1;
	        $data['serial_number'] = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
	        $insert = Db::name("transfer")->insert($data);
	        if($insert){
	        	return $this->apiReturn(['code'=>0,'msg'=>$msg]);
	        }else{
	        	return $this->apiReturn(['code'=>1,'msg'=>$msg]);
	        }
		}else{
			return $this->apiReturn(['code'=>1,'msg'=>$msg]);
		}
	}

	//获取倒计时订单
	public function get_waiting_recharge(){
        $mid = input('wallet_id');
		$userid = decoded_user_token(input("user_token"),'member_id');
		return $this->apiReturn(['code'=>1,'msg'=>'暂时无法获取地址']);
		if($mid == 6 || $mid == 8){
			$waiting_time = 1200;
		}else{
			$waiting_time = 1200;
		}
		$waiting_order_address = Db::name("recharge_address")->where(["wallet_id"=>$mid,"user_id"=>$userid,"create_time"=>["gt",time()-$waiting_time]])->find();
		$waiting_order_recharge = Db::name("recharge_auto")->where(["wallet_id"=>$mid,"user_id"=>$userid,"create_time"=>["gt",time()-$waiting_time/2+60]])->find();
		if($waiting_order_recharge){
			return $this->apiReturn(['code'=>0,'data'=>['status'=>1,'left_time'=>$waiting_order_address['create_time']+$waiting_time-time(),'plan_detail'=>$waiting_order_recharge],'msg'=>'查询成功']);
		}
		if($waiting_order_address){
			return $this->apiReturn(['code'=>0,'data'=>['status'=>0,'left_time'=>$waiting_order_address['create_time']+$waiting_time-time(),'plan_detail'=>$waiting_order_address],'msg'=>'查询成功']);
		}
		return $this->apiReturn(['code'=>0,'data'=>null,'msg'=>'无倒计时数据']); 
    }

	//获取用户地址
	public function get_user_address(){
	    $mid = input('wallet_id');
        $userid = decoded_user_token(input("user_token"),'member_id');
		if($mid == 6 || $mid == 8){
			$waiting_time = 600;
		}else{
			$waiting_time = 600;
		}
        if(empty($mid)){
            return $this->apiReturn(['code'=>1,'msg'=>'货币id不得为空']);
        }
	    $address = Db::name("user_account")->where(["user_id"=>$userid,"wallet_id"=>$mid])->find();
	    if(empty($address)){
            return $this->apiReturn(['code'=>1,'msg'=>'地址不存在']);
        }
        $data = array(
			"wallet_id" => $mid,
			"user_id" => $userid,
			"create_time" =>time(),
			"update_time" =>time(),
			'address' => $address['blockchain_address2']
		);
		$res = Db::name("recharge_address")->insert($data);
		if($res){
			return $this->apiReturn(['code'=>0,'data'=>['address_id'=>$res,'address'=>$address['blockchain_address2'],'left_time'=>$waiting_time],'msg'=>'获取成功']);
		}else{
			return $this->apiReturn(['code'=>1,'msg'=>'获取失败']);
		}
	    
        
	}
	
	//采集记录添加
	public function add_recharge_record(){
		$address = input('address');
		$mid = input('mid');
		$userid = decoded_user_token(input("user_token"),'member_id');
		if($mid == 6 || $mid == 8){
			$waiting_time = 300;
		}else{
			$waiting_time = 600;
		}
		$data = array(
            'user_id' => $userid,
            'wallet_id' => $mid,
            'address' => $address,
            'create_time' => time(),
            'collect_time' => time()
        );
	    $res = Db::name("recharge_auto")->insert($data);
	    if($res){
            return $this->apiReturn(['code'=>0,'data'=>['recharge_id'=>$res,'left_time'=>$waiting_time],'msg'=>'获取成功']);
        }else{
            return $this->apiReturn(['code'=>1,'msg'=>'获取失败']);
        }
	}

    public function get_recharge_status(){
		$mid = input("wallet_id");


		$address_id = input("address_id");
        $recharge_record = Db::name("recharge_auto")->where(["address_id"=>$address_id,"wallet_id"=>$mid,'query_status'=>0])->find();
        if(empty($recharge_record)){
            return $this->apiReturn(['code'=>1,'msg'=>'采集记录不存在']);
        }else{
			Db::name("recharge_auto")->where(["id"=>$recharge_record["id"]])->update(["query_status"=>1]);
            return $this->apiReturn(['code'=>0,'data'=>$recharge_record,'msg'=>'查询成功']);
        }
    }

}
